<?php

namespace app\webapi\controller;

use think\facade\Cache;
use think\facade\Db;
use think\facade\Request;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
header("Access-Control-Allow-Origin: http://localhost:8080");
//header("Access-Control-Allow-Origin: http://fgreat.baihuahui.top");
header("Access-Control-Allow-Credentials: true");
class ApiBaseController extends \app\BaseController
{
    // const KEYS = [
    //     'RUSH_SCHEDULE' => "rush_schedule",
    //     'RUSH_GOODS' => "rush_goods_",
    //     'RUSH_GOODS_COUNTER' => "counter_rush_goods_",
    //     'USER_SMS' => "user_sms",
    //     'USER_GODTIME' => "user_godtime_",
    //     'USER_BLACKLIST' => "user_blacklist_",
    //     'USER_BLACKROOM' => "user_blackroom_",
    //     'USER_LIMIT' => "user_limit_",
    //     'USER_BELONG' => "user_blong",
    //     'USER_COMMON_LIMIT' => "user_common_limit",
    //     'USER_BADLIST' => "user_bad_",
    //     'SHELVES_GOODS' => "shelves_goods_",
    //     'SHELVES_GOODS_COUNTER' => "counter_shelves_goods",
    //     'BANNER_LIST' => "banner_list",
    //     'NOTICE_LIST' => "notice_list",
    //     'CATEGORY_LIST' => "category_list",
    //     'PROTOCOL_LIST' => "protocol_no_",
    //     'RATE_HANHDING' => "rate_handling_fee",
    //     'BUCKET_GOODS_LIST' => "bucket_goods_list_",
    //     'TOKEN' => "token_",
    //     'ADMIN_TOKEN' => "admin_token_",
    //     'GOODS_LAUNCH_TIME' => "goods_launch_time",
    //     'ALL_GOODS_LAUNCH_STATE' => 'all_goods_luanch_state',
    //     'GOODS_LAUNCH_GAIN' => "goods_luanch_gain",
    //     'LOG_SCHEDULE' => "LOG_S_",
    //     'LOG_SCHEDULE_RUSH_OK' => "LOG_S_OK_",
    //     'md5key' => "free",
    // ];
    public $key = 'mango';
    public $expTime = 86400 * 365;

    protected function apiDate($type = 'Y-m-d H:i:s')
    {
        return date($type, time());
    }

    protected function createToken($uid)
    {
//        return md5($uid . self::KEYS['md5key']);
        $nowTime = time();
        $token['iss'] = ''; //签发者 可选
        $token['aud'] = ''; //接收该JWT的一方，可选
        $token['iat'] = $nowTime; //签发时间
        $token['nbf'] = $nowTime + 30; //某个时间点后才能访问
        $token['exp'] = $nowTime + $this->expTime; //token过期时间,这里设置2个小时
        $token['id'] = $uid; //自定义参数
        $json = JWT::encode($token, $this->key, "HS256");
        return $json;

    }

 protected function checkToken($is_return = true)
    {
        $token = Request::param('token');
        if ($token) {
            try {
                JWT::$leeway = 60; //当前时间减去60，把时间留点余地
                $decoded = JWT::decode($token, new Key($this->key, 'HS256')); //HS256方式，这里要和签发的时候对应
                $arr = (array)$decoded;
                if (!isset($arr['id'])) {
                    $this->result_user_error("token错误", [], $is_return);
                }
                $user_info = null;
                // 先从Redis中获取，没有的话再查数据库
//                $radata = Cache::store('redis')->get(self::KEYS['TOKEN'] . $arr['id']);
                $radata = APiRedisServer::selected(1)->get(self::KEYS['TOKEN'] . $arr['id']);
                if (!empty($radata)) {
                    $user_info = json_decode($radata, true);
                } else {
                    $user_info = Db::name('user')->where('id', $arr['id'])->find();
                    if (empty($user_info)) {
                        $this->result_user_error("没有找到用户", [], $is_return);
                    } else {
                        unset($user_info['pwd_md5']);
                        unset($user_info['admin_pwd']);
                        $user_info['roles'] = json_decode($user_info['roles'], true);
                        $alist = Db::name('user_address')->where('uid', $user_info['id'])->select()->toArray();
                        $user_info['address_list'] = $alist;
//                        Cache::store('redis')->set(self::KEYS['TOKEN'] . $arr['id'], json_encode($user_info), 86400 * 10);
                        APiRedisServer::selected(1)->set(self::KEYS['TOKEN'] . $arr['id'], json_encode($user_info), 86400 * 10);
                    }
                }
                if (!empty($user_info['token']) && $user_info['token'] == $token) {
                    if (!$user_info['state'] > 0) {
                        $this->result_user_error("登录失败", [], $is_return);
                    }
                    //登录成功
                    return $user_info;
                } else {
                    $this->result_user_error("登录已失效,请重新登录", [], $is_return);
                }

            } catch (\Exception $e) {
                $this->result_user_error("登录已失效,请重新登录", [], $is_return);
            }
        } else {
            $this->result_user_error("用户未登录", [], $is_return);
        }

    }

    public function updateUserInfo($uid, $admin = 0)
    {

        $user_info = Db::name('user')->where('id', $uid)->find();
        if (!empty($user_info)) {
            unset($user_info['pwd_md5']);
            unset($user_info['admin_pwd']);
            $user_info['roles'] = json_decode($user_info['roles'], true);
            $alist = Db::name('user_address')->where('uid', $uid)->select()->toArray();
            $user_info['address_list'] = $alist;
            if ($admin) {
                //暂时不写

            }

//            Cache::store('redis')->set(self::KEYS['TOKEN'] . $uid, json_encode($user_info), 86400 * 10);
            APiRedisServer::selected(1)->setex(self::KEYS['TOKEN'] . $uid, 86400 * 10, json_encode($user_info));
        }
    }


    protected function result_ok($msg = '', $data = [])
    {
        echo json_encode(['res_code' => 1, 'msg' => $msg, 'data' => $data], JSON_UNESCAPED_UNICODE);
        exit;
    }

    protected function result_error($msg = '未知错误', $data = [], $is_return = true)
    {
        if ($is_return) {
            echo json_encode(['res_code' => -1, 'msg' => $msg, 'data' => $data], JSON_UNESCAPED_UNICODE);
            exit;
        } else {
            return ['res_code' => -1, 'msg' => $msg, 'data' => $data];
        }

    }

    protected function result_user_error($msg = '未知错误', $data = [], $is_return = true)
    {
        if ($is_return) {
            echo json_encode(['res_code' => -900, 'msg' => $msg, 'data' => $data], JSON_UNESCAPED_UNICODE);
            exit;
        } else {
            return ['res_code' => -900, 'msg' => $msg, 'data' => $data];
        }
    }

    protected function result_warning($msg = '未知错误', $data = [])
    {
        echo json_encode(['res_code' => 0, 'msg' => $msg, 'data' => $data], JSON_UNESCAPED_UNICODE);
        exit;
    }
    /**
     * // 返回错误
     * base.result_user_error = function (msg, data) {
     * return { res_code: -900, msg, data };
     * }
     *
     * // 返回警告
     * base.result_warning = function (msg, data) {
     * return { res_code: 0, msg, data };
     * }
     *
     * // 返回正确
     * base.result_ok = function (msg, data) {
     * return { res_code: 1, msg, data };
     * }
     */
}